package com.ailk.evaluation.evaluation;

import java.util.HashMap;
import java.util.Vector;

public class EvaluationTemplateHtmlHelper {

	private EvaluationTemplate template;
	private String[] head;
	private EvaluationTemplateHtmlTableCell[][] table;

	public EvaluationTemplateHtmlHelper(EvaluationTemplate template){
		this.setTemplate(template);
	}
	
	public EvaluationTemplate getTemplate() {
		return template;
	}

	public void setTemplate(EvaluationTemplate template) {
		if(template != null){
			this.template = template;
			generateHtmlTable(template);
		}
	}

	public String[] getHead() {
		return head;
	}

	public EvaluationTemplateHtmlTableCell[][] getTable() {
		return table;
	}
	
	public int getLevelCount() {
		return head.length;
	}
	
	private void generateHtmlTable(EvaluationTemplate template){
		head = generateHtmlTableHead(template);
		table = generateHtmlTableBody(template);
	}
	
	private EvaluationTemplateHtmlTableCell[][] generateHtmlTableBody(EvaluationTemplate template){
		EvaluationEntry[] leafEntries = template.getLeafEntries();
		HashMap<String,EvaluationEntry> allEntries = new HashMap<String,EvaluationEntry>();
		
		EvaluationTemplateHtmlTableCell[][] tableBody = new EvaluationTemplateHtmlTableCell[leafEntries.length][];
		for(int i = 0; i < leafEntries.length; i++){
			Vector<EvaluationTemplateHtmlTableCell> tableRow = new Vector<EvaluationTemplateHtmlTableCell>();
			EvaluationEntry currentEntry= leafEntries[i];
			while(currentEntry != null){
				if(!allEntries.containsKey(currentEntry.getId())){
					allEntries.put(currentEntry.getId(), currentEntry);
					tableRow.add(0, new EvaluationTemplateHtmlTableCell(currentEntry, template.getLeafCount(currentEntry), template.getEntryLevel(currentEntry)));
				}
				
				currentEntry = template.getParentEntry(currentEntry);
			}
			
			if(tableRow.size() > 0){
				EvaluationTemplateHtmlTableCell[] tableRowArray= new EvaluationTemplateHtmlTableCell[tableRow.size()];
				tableRow.toArray(tableRowArray);
				tableBody[i] = tableRowArray;
			}
		}
		
		return tableBody;

	}
	
	private String[] generateHtmlTableHead(EvaluationTemplate template){
		Vector<String> head = new Vector<String>();
		
		EvaluationEntry[] rootEntries = template.getRootEntries();
		EvaluationEntry[] currentRow;
		
		if(rootEntries.length > 0){
			currentRow = rootEntries;
        }else{
        	currentRow = null;
        }
		
		 while(currentRow != null){
			 head.add(currentRow[0].getTypeName());
			 currentRow = template.getChildrenEntries(currentRow[0]);
		 }
		 
		 if(head.size() > 0){
			 String[] headArray = new String[head.size()];
			 head.toArray(headArray);
			 return headArray;
		 }else{
			 return null;
		 }

	}
}
